var Config = require('config');
var Co = require('constant');
var pomelo = require('pomelo-client');
var SingleEventTarget = require('SingleEventTarget');
var PomeloNet = function () {
    //APP数据
    this.name = "i am PomeloNet";
};
var pro = PomeloNet.prototype;

function pomeloRequest(route,msg,cb){
	cc.log("发送消息",msg);
	pomelo.request(route, msg, function(data) {
		if(data.code === 500) {
			cc.error('pomeloNet',data.code);
		}else{
			cc.log("收到消息",data);
			cb(data);
		}            
	});
};
// query connector
function queryEntry(userData, callback) {
	var route = 'gate.gateHandler.queryEntry';
	pomelo.init({
		host: Config.gateHost,
		port: Config.gatePort,
		log: true
	}, function() {
		pomeloRequest(route,{userData:userData},function(data) {
			pomelo.disconnect();
			callback(data.host, data.port);
		});
	});
};
pro.init = function (userData) {
	queryEntry(userData, function(host, port) {
        pomelo.init({
            host: host,
            port: port,
            log: true
        }, function(data) {
			SingleEventTarget.dispatchCustomEvent(Co.MSG_SOCKET_ONOPEN,data);
        });
    });
};
pro.login = function(userData){
	var route = 'login.loginHandler.login';
	pomeloRequest(route,{userData:userData},function(data) {
		SingleEventTarget.dispatchCustomEvent(Co.MSG_LOGIN,data);
	});
}
module.exports = new PomeloNet();



